<template>
  <div class="user-profile-page">
    <!-- 粒子效果 -->
    <div class="header-particles">
      <div class="particle" v-for="n in 20" :key="n"></div>
    </div>
    
    <div class="user-main-container">
      <index-frame></index-frame>

      <div class="content-area">
        <div class="main-content">
          <div class="personal-info-section">
            <!-- 头像和三项数据 -->
            <div class="profile-header-row">
              <div class="avatar-upload">
                <img :src="userAvatar" alt="Avatar" class="editable-avatar" />
              </div>
              <div class="profile-stats-row">
                <div class="profile-stat">
                  <div class="stat-value">{{ likes }}</div>
                  <div class="stat-label">🌟 获赞</div>
                </div>
                <div class="profile-stat">
                  <div class="stat-value">{{ follows }}</div>
                  <div class="stat-label">🌈 关注</div>
                </div>
                <div class="profile-stat">
                  <div class="stat-value">{{ fans }}</div>
                  <div class="stat-label">🍃 粉丝</div>
                </div>
              </div>
              <!-- 关注按钮 - 只有不是自己才显示 -->
              <el-button
                v-if="!isMyself"
                :type="isFollowing ? 'info' : 'primary'"
                :size="'default'"
                :loading="followLoading"
                @click="toggleFollow"
                class="follow-button"
                :class="{ 'followed': isFollowing }"
              >
                <i :class="isFollowing ? 'el-icon-check' : 'el-icon-plus'"></i>
                {{ isFollowing ? '已关注' : '关注' }}
              </el-button>
            </div>

            <!-- 信息展示 -->
            <div class="form-group">
              <label>👤 用户名</label>
              <span class="readonly-value">{{ userName || '未填写' }}</span>
            </div>
            <div class="form-group">
              <label>📅 出生日期</label>
              <span class="readonly-value">{{ dateOfBirth || '未填写' }}</span>
            </div>
            <div class="form-group">
              <label>🚻 性别</label>
              <span class="readonly-value">{{ gender === 1 ? '男' : gender === 2 ? '女' : '未填写' }}</span>
            </div>
            <div class="form-group">
              <label>📞 电话</label>
              <span class="readonly-value">{{ contactPhone || '未填写' }}</span>
            </div>
            <div class="form-group">
              <label>📧 邮箱</label>
              <span class="readonly-value">{{ userEmail || '未填写' }}</span>
            </div>
            <div class="form-group">
              <label>🌱 一句话</label>
              <span class="readonly-value">{{ signature || '未填写' }}</span>
            </div>
            <div class="form-group">
              <label>📘 简介</label>
              <span class="readonly-value" style="white-space: pre-line;">{{ personalIntroduction || '未填写' }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import IndexFrame from '../../indexFrame.vue';
import axios from 'axios';

export default {
  name: 'UserProfileView',
  components: {
    IndexFrame
  },
  data() {
    return {
      userId: null,
      userName: "",
      userAvatar: "https://via.placeholder.com/100",
      signature: "",
      gender: null,
      contactPhone: "",
      personalIntroduction: "",
      userEmail: "",
      dateOfBirth: "",
      likes: 0,
      follows: 0,
      fans: 0,
      isFollowing: false,
      isMyself: false,
      followLoading: false, // 关注按钮加载状态
      currentUserId: null // 当前登录用户ID
    };
  },
  async mounted() {
    await this.initializeData();
  },
  methods: {
    async initializeData() {
      const userId = this.$route.params.id;
      this.currentUserId = Number(localStorage.getItem("userId"));
      
      if (!userId) {
        this.$message.error("用户ID不能为空");
        return;
      }

      try {
        await this.loadUserProfile(userId);
        await this.loadUserStats(userId);
        await this.checkFollowStatus(userId);
      } catch (error) {
        console.error("初始化用户数据失败:", error);
        this.$message.error("加载用户信息失败");
      }
    },

    // 加载用户基本信息
    async loadUserProfile(userId) {
      const res = await axios.get(`http://localhost:8080/mw/UserById?id=${userId}`);
      const user = res.data || {};
      
      this.userId = user.userId;
      this.userName = user.userName;
      this.userAvatar = user.userAvatar || "https://via.placeholder.com/100";
      this.signature = user.signature;
      this.gender = user.gender;
      this.contactPhone = user.contactPhone;
      this.personalIntroduction = user.personalIntroduction;
      this.userEmail = user.userEmail;
      this.dateOfBirth = user.dateOfBirth;
      this.isMyself = Number(this.currentUserId) === Number(userId);
    },

    // 加载用户统计数据
    async loadUserStats(userId) {
      try {
        // 获取点赞数
        await this.loadLikesCount(userId);
        
        // 获取关注数和粉丝数
        await this.loadFollowStats(userId);
      } catch (error) {
        console.error("加载用户统计数据失败:", error);
      }
    },

    // 获取点赞统计
    async loadLikesCount(userId) {
      try {
        // 获取用户发布的攻略
        const strategyRes = await axios.get(`http://localhost:8080/ts/listByUser?userId=${userId}`);
        const strategyIds = (strategyRes.data || []).map(item => item.strategyId);

        if (strategyIds.length === 0) {
          this.likes = 0;
          return;
        }

        // 获取所有点赞记录
        const likeRes = await axios.get(`http://localhost:8080/strlike/list`);
        const likeList = likeRes.data || [];
        
        // 计算该用户攻略的总点赞数
        this.likes = likeList.filter(item => strategyIds.includes(item.strategyId)).length;
      } catch (error) {
        console.error("获取点赞数失败:", error);
        this.likes = 0;
      }
    },

    // 获取关注和粉丝统计
    async loadFollowStats(userId) {
      try {
        const followRes = await axios.get(`http://localhost:8080/mw/userFollowList`);
        const followList = followRes.data || [];
        
        // 关注数：该用户关注了多少人
        this.follows = followList.filter(item => item.userId === Number(userId)).length;
        
        // 粉丝数：多少人关注了该用户
        this.fans = followList.filter(item => item.followedUserId === Number(userId)).length;
      } catch (error) {
        console.error("获取关注统计失败:", error);
        this.follows = 0;
        this.fans = 0;
      }
    },

    // 检查关注状态
    async checkFollowStatus(userId) {
      if (!this.currentUserId || this.isMyself) {
        this.isFollowing = false;
        return;
      }

      try {
        // 方法1: 使用专门的检查接口（如果存在）
        try {
          const followRes = await axios.get('http://localhost:8080/mw/checkFollow', {
            params: {
              userId: this.currentUserId,
              followedUserId: Number(userId)
            }
          });
          this.isFollowing = followRes.data;
          return;
        } catch (error) {
          // 如果专门接口不存在，使用方法2
        }

        // 方法2: 从关注列表中查找
        const followRes = await axios.get(`http://localhost:8080/mw/userFollowList`);
        const followList = followRes.data || [];
        
        this.isFollowing = followList.some(item =>
          item.userId === this.currentUserId && item.followedUserId === Number(userId)
        );
      } catch (error) {
        console.error("检查关注状态失败:", error);
        this.isFollowing = false;
      }
    },

    // 切换关注状态
    async toggleFollow() {
      // 检查登录状态
      if (!this.currentUserId) {
        this.$message.warning("请先登录才能关注用户");
        this.$router.push('/login'); // 跳转到登录页
        return;
      }

      // 防止关注自己
      if (this.isMyself) {
        this.$message.warning("不能关注自己哦");
        return;
      }

      this.followLoading = true;

      try {
        if (this.isFollowing) {
          await this.unfollowUser();
        } else {
          await this.followUser();
        }
      } catch (error) {
        console.error("关注操作失败:", error);
        this.$message.error("操作失败，请稍后再试");
      } finally {
        this.followLoading = false;
      }
    },

    // 关注用户
    async followUser() {
      try {
        const followData = {
          userId: this.currentUserId,
          followedUserId: this.userId,
          followedTime: new Date().toISOString()
        };

        // 尝试使用新的关注接口
        let response;
        try {
          response = await axios.post(`http://localhost:8080/mw/addUserFollow`, followData);
        } catch (error) {
          // 如果新接口不存在，尝试使用原来的接口
          response = await axios.post(`http://localhost:8080/mw/follow`, followData);
        }

        if (response.data > 0 || response.status === 200) {
          this.isFollowing = true;
          this.fans++; // 粉丝数+1
          this.$message.success("关注成功");
          
          // 可选：发送关注通知
          await this.sendFollowNotification();
        } else {
          throw new Error('关注失败');
        }
      } catch (error) {
        throw error;
      }
    },

    // 取消关注
    async unfollowUser() {
      try {
        // 尝试使用新的取消关注接口
        try {
          await axios.delete(`http://localhost:8080/mw/deleteByUserAndFollow`, {
            params: {
              userId: this.currentUserId,
              followedUserId: this.userId
            }
          });
        } catch (error) {
          // 如果新接口不存在，尝试使用原来的接口
          await axios.delete(`http://localhost:8080/mw/unfollow`, {
            data: {
              userId: this.currentUserId,
              followedUserId: this.userId
            }
          });
        }

        this.isFollowing = false;
        this.fans--; // 粉丝数-1
        this.$message.success("已取消关注");
      } catch (error) {
        throw error;
      }
    },

    // 发送关注通知（可选功能）
    async sendFollowNotification() {
      try {
        await axios.post(`http://localhost:8080/notification/follow`, {
          fromUserId: this.currentUserId,
          toUserId: this.userId,
          type: 'follow',
          content: '关注了你',
          createdTime: new Date().toISOString()
        });
      } catch (error) {
        console.log('发送关注通知失败:', error);
        // 这里不需要给用户显示错误，因为关注已经成功了
      }
    }
  }
};
</script>

<style scoped>
/* ========== 整体页面样式 ========== */
.user-profile-page {
  padding: 0;
  margin: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  position: relative;
  overflow-x: hidden;
}

.user-profile-page::before {
  content: '';
  position: fixed;
  top: 0; 
  left: 0; 
  right: 0; 
  bottom: 0;
  width: 100vw;
  height: 100vh;
  background: 
    linear-gradient(135deg, rgba(74, 144, 226, 0.8), rgba(107, 91, 149, 0.8)), 
    url('https://images.unsplash.com/photo-1506905925346-21bda4d32df4?ixlib=rb-4.0.3&auto=format&fit=crop&w=2000&q=80') center/cover;
  z-index: 0;
  pointer-events: none;
}

.user-profile-page > * {
  position: relative;
  z-index: 1;
}

/* ========== 粒子效果 ========== */
.header-particles {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 1;
}

.particle {
  position: absolute;
  width: 4px;
  height: 4px;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 50%;
  animation: float 6s ease-in-out infinite;
}

.particle:nth-child(odd) {
  animation-delay: -2s;
}

.particle:nth-child(even) {
  animation-delay: -4s;
}

@keyframes float {
  0%, 100% { transform: translateY(0px) rotate(0deg); opacity: 0; }
  50% { transform: translateY(-100px) rotate(180deg); opacity: 1; }
}

/* ========== 主容器样式 ========== */
.user-main-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  position: relative;
  overflow: hidden;
  padding: 80px 20px 40px 20px;
  box-sizing: border-box;
}

.content-area {
  display: flex;
  justify-content: center;
  align-items: center;
  flex: 1;

}

.main-content {
  width: 100%;
  max-width: 800px;
  backdrop-filter: blur(16px) saturate(180%);
  -webkit-backdrop-filter: blur(16px) saturate(180%);
  background-color: rgba(255, 255, 255, 0.85);
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  border: 1px solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
  position: relative;
  z-index: 2;
}

.main-content:hover {
  background-color: rgba(255, 255, 255, 0.9);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.2);
}

.personal-info-section h2 {
  font-size: 30px;
  color: #2e7d32;
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 12px;
  border-bottom: 2px dashed #a5d6a7;
}

.profile-header-row {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 60px;
  margin-bottom: 30px;
}

.avatar-upload .editable-avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid #d9d0ff;
  box-shadow: 0 4px 14px rgba(185, 99, 187, 0.2);
  transition: transform 0.3s;
}
.avatar-upload .editable-avatar:hover {
  transform: scale(1.05);
}

.profile-stats-row {
  display: flex;
  gap: 30px;
}

.profile-stat {
  text-align: center;
}
.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #46127e;
}
.stat-label {
  font-size: 14px;
  color: #666;
}

.follow-button {
  border-radius: 20px;
  padding: 6px 16px;
  transition: all 0.3s ease;
}
.follow-button:hover {
  background-color: #b860d2;
  color: white;
}

.form-group {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding: 10px 0;
  border-bottom: 1px dashed rgba(0, 0, 0, 0.05);
}

.form-group label {
  width: 120px;
  font-weight: 600;
  color: #521772;
  font-size: 15px;
}

.readonly-value {
  flex: 1;
  padding: 10px 14px;
  font-size: 15px;
  color: #333;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 10px;
  transition: all 0.3s ease;
  box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.08);
}
.readonly-value:hover {
  background: rgba(255, 255, 255, 0.9);
  box-shadow: 0 0 6px rgba(76, 175, 80, 0.15);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-header-row {
    flex-direction: column;
    gap: 20px;
  }
  
  .main-content {
    padding: 20px;
  }
  
  .form-group {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .form-group label {
    width: 100%;
    margin-bottom: 8px;
  }
}
</style>